package com.jgp.security.shiro;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.jgp.security.pojo.UserInfo;
import com.jgp.security.utils.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.credential.CredentialsMatcher;

import java.io.UnsupportedEncodingException;

/**
 * 项目   jgp-cloud-parent
 * 作者   loufei
 * 时间   2019/3/12
 */
@Slf4j
public class JWTCredentialsMatcher implements CredentialsMatcher {
    
    private boolean devMode;
    
    public JWTCredentialsMatcher(boolean devMode) {
        super();
        this.devMode = devMode;
    }
    /**
     * Matcher中直接调用工具包中的verify方法即可
     */
    @Override
    public boolean doCredentialsMatch(AuthenticationToken authenticationToken, AuthenticationInfo authenticationInfo) {
        String token = (String) authenticationToken.getCredentials();
        Object stored = authenticationInfo.getCredentials();
        String salt = stored.toString();
        if(this.devMode){
            return true;
        }
        UserInfo user = (UserInfo)authenticationInfo.getPrincipals().getPrimaryPrincipal();
        try {
            Algorithm algorithm = Algorithm.HMAC256(salt);
            JWTVerifier verifier = JWT.require(algorithm)
                                      .withClaim(JWTUtil.USERNAME_FORM_KEY, user.getUsername())
                                      .build();
            verifier.verify(token);
        } catch (UnsupportedEncodingException | JWTVerificationException e) {
            log.error("Token Error:{}", e.getMessage());
        }
        return false;
    }
}
